package com.springboot.config.aop;

import com.springboot.config.annotion.BusinessLog;
import com.springboot.config.tool.ToolUtil;
import com.springboot.project.common.entity.Log;
import com.springboot.project.common.entity.User;
import com.springboot.project.common.service.impl.LogServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    LogServiceImpl logService;


    @Pointcut("@annotation(com.springboot.config.annotion.BusinessLog)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //异步保存日志
        try {
            saveLog(point, time);
        } catch (Exception e) {
            logger.error("日志记录出错!", e);
        }
        return result;
    }

    void saveLog(ProceedingJoinPoint joinPoint, long time) throws Exception {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log sysLog = new Log();
        BusinessLog syslog = method.getAnnotation(BusinessLog.class);
        if (syslog != null) {
            // 注解上的描述
            sysLog.setOperation(syslog.value());
        }
        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        //获取拦截方法的参数
        Object[] params = joinPoint.getArgs();
        StringBuilder sb = new StringBuilder();
        for (Object param : params) {
            sb.append(param);
            sb.append(" & ");
        }
        sysLog.setDetail(sb.toString());

        // 获取request
        HttpServletRequest request = ToolUtil.getHttpServletRequest();
        // 设置IP地址
        sysLog.setIp(ToolUtil.getIpAddr(request));
        // 用户名
        User user = (User) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        if(user != null)
        {
            sysLog.setUserId((long)(user.getId()));
            sysLog.setUsername(user.getUsername());
        }
        sysLog.setTime((int) time);
        // 系统当前时间
        Date date = new Date();
        sysLog.setCreateTime(date);
        sysLog.setType(1);
        // 保存系统日志
        logService.insert(sysLog);
    }
}
